import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

import { AlertController } from '@ionic/angular';
import { createGesture, Gesture } from '@ionic/core';

import { TabsService } from 'src/app/shared/service/tabs.service';

import { AppGlobalService } from "./../../shared/service/app-global.service";
import { EventService } from './../../shared/service/event.service';
import { HttpService } from "../../shared/service/http.service";
import { ChatService } from 'src/app/shared/service/chatService';

@Component({
  selector: 'app-customer-details',
  templateUrl: './customer-details.component.html',
  styleUrls: ['./customer-details.component.scss'],
})
export class CustomerDetailsComponent implements OnInit, OnDestroy {
  // 组件数据
  @Input() tagData: any = {};
  isShow = false;
  test: any = {
    "type": "page",
    "style": "page.CustomInfoPageLogic",
    "name": null,
    "data": {
      "labelTag": {
        "submit": {
          "id": "6d0fc81b-1008-4036-809b-cd87b670f241",
          "content": {
            "id": "5ebb961b8f110f000187a2a1"
          }
        },
        "parentData": [
          {
            "name": "信息无效",
            "id": "3",
            "check": false,
            "isRadio": "1",
            "child": [

            ]
          },
          {
            "name": "有兴趣了解",
            "id": "9",
            "check": true,
            "isRadio": "1",
            "child": [
              {
                "name": "装修价格",
                "id": "27",
                "check": true,
                "isRadio": "0"
              },
              {
                "name": "装修方案",
                "id": "28",
                "check": true,
                "isRadio": "0"
              },
              {
                "name": "装修质量",
                "id": "29",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "装修质保",
                "id": "30",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "实地考察",
                "id": "31",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "地理位置",
                "id": "20",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "入驻费",
                "id": "21",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "商业氛围",
                "id": "22",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "行业前景",
                "id": "13",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "发展趋势",
                "id": "14",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "加盟费",
                "id": "10",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "品牌产品",
                "id": "11",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "运营方法",
                "id": "12",
                "check": true,
                "isRadio": "0"
              }
            ]
          },
          {
            "name": "没有意向",
            "id": "1",
            "check": false,
            "isRadio": "1",
            "child": [
              {
                "name": "加盟费太高",
                "id": "5",
                "check": false,
                "isRadio": "0"
              },
              {
                "name": "目前不经商",
                "id": "41",
                "check": false,
                "isRadio": "1"
              }
            ]
          }
        ],
        "title": "客户标记"
      },
      "userInfo": {
        "opportunity_id": "5ebb65c74673ef0001b383ac",
        "submit": {
          "id": "7b29b715-f4c3-428c-ad03-1400c151abbd",
          "label": "查看电话",
          "content": {

          }
        },
        "phone": "183****2631",
        "name": "唐大大",
        "logo": "",
        "customer_id": "5d106a1aafdcd900014d6ede"
      },
      "recommen": {
        "label": "客服推荐",
        "content": "唐小姐经营有道"
      },
      "customRemark": {
        "submit": {
          "id": "0dd741cb-a3b5-4272-b31c-1eaaf18dd981",
          "content": {
            "text": "text",
            "id": "5ebb961b8f110f000187a2a1"
          }
        },
        "label": "您可以加备注以便下次跟进客户"
      },
      "opportunity": {
        "title": "转让店铺",
        "describe": {
          "title": "描述",
          "content": "啊啊啊啊啊"
        },
        "items": [
          {
            "small": "",
            "label": "物业类型",
            "content": "临街商铺"
          },
          {
            "small": "已停业",
            "label": "目前经营",
            "content": "餐馆"
          }
        ]
      },
      "prelink": {
        "link": {
          "type": "page",
          "params": {
            "index": "1",
            "id": 1
          },
          "target": "143064"
        }
      },
      "remark": {
        "item": [
          {
            "datetime": "2020-05-13 15:14:47",
            "content": "哎哎哎啊"
          },
          {
            "datetime": "2020-05-13 15:14:38",
            "content": "哈哈哈"
          },
          {
            "datetime": "2020-05-13 15:14:20",
            "content": "测试备注"
          },
          {
            "datetime": "",
            "content": "测试插入"
          },
          {
            "datetime": "",
            "content": "111"
          },
          {
            "datetime": "",
            "content": "333"
          }
        ],
        "title": "备注记录"
      },
      "customInfo": {
        "tagname": "擅长经营",
        "pluginId": "转让客户",
        "skill": "火锅店,餐馆,干锅火锅",
        "name": "唐大大",
        "signed": "无意向",
        "unSignOper": {
          "link": {
            "type": "page",
            "params": {
              "id": "1231231"
            },
            "target": "143060"
          },
          "label": "与TA签约",
          "tagLabel": "成交额越高，客户越多！"
        },
        "certification": "认证"
      },
      "nextlink": {
        "link": {
          "type": "page",
          "params": {
            "index": "0"
          },
          "target": "143064"
        }
      }
    }
  };
  // tag多层
  tagParent: any = undefined;
  tagChild: any = undefined;
  tagGrandson: any = undefined;
  // 备注
  remarksList: any = [];
  remarksText = "";

  userData: any = undefined;

  // 筛选及页面数据参数
  params: any = {};
  // 当前页数，默认1
  pageNo = 1;
  // size
  pageSize: number;
  // 数量
  pageTotal: number;
  checkBgPre = false;
  checkBgNext = false;
  infoAll = true;
  num: any = 0;
  interval: any;




  constructor(
    public router: Router,
    public alertController: AlertController,
    private http: HttpService,
    private eventService: EventService,
    private webSocketTalk: ChatService,
    private appGlobalService: AppGlobalService) { }

  ngOnInit() {
    // this.tagData = this.test;
    console.log(this.tagData);
    // console.log(this.test);

    // tag
    this.tagParent = this.tagData.data.labelTag.parentData;
    console.log(this.tagParent);
    // 备注列表
    this.remarksList = this.tagData.data.remark.item;

    // 上拉触件 direction:拉动方向
    const gesture: Gesture = createGesture({
      el: document.getElementById('gestureBox'),
      threshold: 15,
      direction: 'y',
      gestureName: 'my-gesture',
      onMove: ev => this.onMoveHandler(ev)
    });
    gesture.setDisabled(false);
    // onMoveHandler节流 简易版
    this.interval = setInterval(() => {
      this.num = 0;
    }, 3900);
  }
  ngOnDestroy() {
    clearInterval(this.interval);
  }


  onMoveHandler(ev) {
    const deltaY = ev.deltaY;
    // console.log(ev);
    if (deltaY < -25) {
      this.num++;
      if (this.num < 2) {
        console.log('上拉加载--------------------------');
        document.getElementById('checkBgNext').style.display = 'block';
        setTimeout(() => {
          // 请求获取新数据
          let index = Number(this.tagData.data.nextlink.link.params.index);
          index++;
          const nextlink = this.tagData.data.nextlink.link.params;
          nextlink.index = index;
          console.log(this.tagData.data.nextlink.link.params);
          const params = {
            pageId: this.tagData.data.nextlink.link.target,
            params: nextlink,
            sessionId: localStorage.getItem('sessionId')
          };
          this.http.post('application/page', params, res => {
            if (res !== undefined) {
              console.log(res);
              this.tagData = JSON.parse(res['script']).views[0].tags[0];
              this.eventService.eventEmit.emit("userInfo", JSON.stringify(this.tagData.data.userInfo));
              this.remarksList = this.tagData.data.remark.item;
            }
          });
          document.getElementById('checkBgNext').style.display = 'none';
        }, 925);
      }
    }
  }

  // 跳转
  clickLink(obj) {
    if (!obj) {
      console.log('没有返回link-target');
    }
    const pageParams = {
      pageId: obj.target,
      params: obj.params,
      sessionId: localStorage.getItem('sessionId')
    };
    this.appGlobalService.goToForward(pageParams);
  }

  clickTag(e, type) {
    // 第一层
    if (e && e.id && type === 1) {
      const nowId = e.id;
      // 改变check 变颜色
      console.log(this.tagParent);
      this.tagParent.forEach(element => {
        if (element.id !== nowId) {
          element.check = false;
        } else {
          element.check = !element.check;
          if (element.check === false) {
            this.tagChild = undefined;
            this.tagGrandson = undefined;
          }
        }
      });
      this.tagParent = JSON.parse(JSON.stringify(this.tagParent));
      console.log(e && e.child && e.check, e.check);
      // 生成子数组
      if (e && e.child && e.check) {
        this.tagChild = e.child;
      } else {
        this.tagChild = undefined;
        this.tagGrandson = undefined;
      }
      // 请求
      let tempIdArr: any = [];
      this.tagParent.forEach(element => {
        if (element.check == true) {
          tempIdArr.push(element.id);
        }
      });
      if (tempIdArr.length > 0) {
        const params = {
          content: { text: e.id, id: this.tagData.data.labelTag.submit.content.id },
          id: this.tagData.data.labelTag.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.http.post("application/submit", params, res => {
          if (res.success) {
            console.log(res);
          }
        });

      }
    } else if (e && e.id && type === 2) {
      // 第二层
      const nowId = e.id;
      const nowRadio = e.isRadio;
      let tempIdArr: any = [];
      // 改变check 变颜色
      this.tagChild.forEach(element => {
        // isRadio 0多选 1单选
        if (element.isRadio == 0) {
          if (element.id === nowId) {
            element.check = !element.check;
            if (element.check === false) {
              this.tagGrandson = undefined;
            }
          }
        } else {
          if (element.id !== nowId) {
            if (nowRadio == 1) {
              element.check = false;
            }
          } else {
            element.check = !element.check;
            if (element.check === false) {
              this.tagGrandson = undefined;
            }
          }
        }
      });
      this.tagChild = JSON.parse(JSON.stringify(this.tagChild));
      // 生成子数组
      if (e && e.child && e.check) {
        this.tagGrandson = e.child;
      } else {
        this.tagGrandson = undefined;
      }
      // 请求
      this.tagParent.forEach(element => {
        if (element.check == true) {
          tempIdArr.push(element.id);
        }
      });
      this.tagChild.forEach(element => {
        if (element.check == true) {
          tempIdArr.push(element.id);
        }
      });
      if (tempIdArr.length > 0) {
        tempIdArr = tempIdArr.toString();
        const params = {
          content: { text: tempIdArr, id: this.tagData.data.labelTag.submit.content.id },
          id: this.tagData.data.labelTag.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.http.post("application/submit", params, res => {
          if (res.success) {
            console.log(res);
          }
        });

      }
    } else if (e && e.id && type === 3) {
      // 第三层
      const nowId = e.id;
      // 改变check 变颜色
      this.tagGrandson.forEach(element => {
        if (element.id !== nowId) {
          element.check = false;
        } else {
          element.check = !element.check;
        }
      });
      this.tagGrandson = JSON.parse(JSON.stringify(this.tagGrandson));
    }
  }

  formatDate(e) {
    const date = new Date(e);
    const YY = date.getFullYear() + '-';
    const MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    const DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    const hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    const mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    const ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return YY + MM + DD + " " + hh + mm + ss;
  }

  // 备注
  addRemark() {
    if (this.remarksText === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.tagData.data.customRemark.submit.content;
    contentArray["text"] = this.remarksText;
    const params = {
      content: contentArray,
      id: this.tagData.data.customRemark.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };

    this.http.post("application/submit", params, res => {
      if (res.success) {
        console.log(res);
        // 本地添加记录
        this.remarksList.push({
          datetime: this.formatDate((new Date())),
          content: this.remarksText
        });
        console.log(this.remarksList);
        this.remarksText = "";
      } else {
        this.appGlobalService.showToast(res.message, 1000, "top");
      }
    });
  }

  /**
   * user按钮
   */
  async userSubmit(uid, con) {
    console.log(uid, con);
    const alert = await this.alertController.create({
      header: '',
      subHeader: '',
      message: '确定要查看号码吗？',
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: () => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          const params = {
            content: con,
            id: uid,
            sessionId: localStorage.getItem("sessionId")
          };
          this.http.post("application/submit", params, res => {
            if (res.success) {
              console.log(res);
              // this.userData = { "phone": "18378082631",
              // "text1": "在线聊",
              // "text2": "打电话" };
              this.userData = res.data;
              // 这么改没问题
              this.tagData.data.userInfo.phone = this.userData.phone;
            } else {
              this.appGlobalService.showToast(res.message, 1000, "top");
            }
          });
        }
      }]
    });
    await alert.present();
  }

  clickInfoAll() {
    this.infoAll = !this.infoAll;
  }

  // 打电话
  async call(e) {
    const alert = await this.alertController.create({
      header: '',
      subHeader: '',
      message: e,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: () => {
          console.log('取消');
        }
      }, {
        text: '拨打',
        cssClass: 'LJ',
        handler: () => {
          this.http.changeCallNumber(e);
        }
      }]
    });
    await alert.present();
  }

  // 聊天
  chat(obj, loginPage) {
    const cityId = JSON.parse(localStorage.getItem('position')) ? JSON.parse(localStorage.getItem('position')).code : 4403;
    if (localStorage.getItem('userId')) {
      this.http.getImId(obj.params.opportunity_id,
        obj.params.customer_id, cityId, (item) => {
          if (item.toId !== localStorage.getItem('userId')) {
            this.webSocketTalk.enterTheChatRoomUseUserId = item.toId;
            if (this.webSocketTalk.enterTheChatRoomUseUserId !== '') {
              localStorage.setItem('enterChatRoomByUserId', '1');
              this.eventService.eventEmit.emit('enterChatRoomByUserId',  
                { userId: this.webSocketTalk.enterTheChatRoomUseUserId, fromFriendList: true } );
            }
          }
        });
    } else if (loginPage) {
      const pageParams = {
        pageId: loginPage,
        params: { skip: 0 },
        sessionId: localStorage.getItem('sessionId')
      };
      localStorage.setItem('isDetailPage', 'true');
      this.appGlobalService.goToForward(pageParams);
    }
  }

  // 上拉加载
  // loadMoreData(event) {
  //   console.log('上拉加载--------------------------');
  //   this.checkBgNext = true;
  //   // 请求获取新数据
  //   setTimeout(() => {
  //     const params = {
  //       pageId: this.tagData.data.nextlink.link.target,
  //       params: { pageNo: Number(this.tagData.data.nextlink.link.params.pageNo) + 1 },
  //       sessionId: localStorage.getItem('sessionId')
  //     };
  //     this.http.post('application/page', params, res => {
  //       if (res !== undefined) {
  //         console.log(res);
  //         this.tagData = JSON.parse(res['script']).views[0].tags[0];
  //       }
  //     });
  //     event.target.complete();
  //     this.checkBgNext = false;
  //     document.getElementById('customer_details_scroll_id').style.display = 'none';
  //   }, 900);
  // }
  // 下拉刷新
  doRefresh(event) {
    console.log('下拉刷新--------------------------');
    document.getElementById('customer_details_hid').style.marginTop = "30px";
    this.checkBgPre = true;
    setTimeout(() => {
      let index = Number(this.tagData.data.prelink.link.params.index);
      index--;
      const prelink = this.tagData.data.prelink.link.params;
      if (index < 0) {
        this.appGlobalService.showToast("当前已经是第一条了", 1000, "top");
      } else {
        prelink.index = index;
        console.log(this.tagData.data.prelink.link.params);
        const params = {
          pageId: this.tagData.data.prelink.link.target,
          params: prelink,
          sessionId: localStorage.getItem('sessionId')
        };
        this.http.post('application/page', params, res => {
          if (res !== undefined) {
            console.log(res);
            this.tagData = JSON.parse(res['script']).views[0].tags[0];
            this.eventService.eventEmit.emit("userInfo", JSON.stringify(this.tagData.data.userInfo));
            this.remarksList = this.tagData.data.remark.item;
          }
        });

      }
      event.target.complete();
      document.getElementById('customer_details_hid').style.marginTop = "0px";
      this.checkBgPre = false;
    }, 900);
  }

}
